package com.zmj.tl.database.taos.highvolume;

import com.zmj.tl.database.taos.config.TdengineConfig;
import com.zmj.tl.database.taos.listener.IotKafkaListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.*;

/**
 * @author zhangjp
 * @version 1.0
 * @title DataBaseMonitor
 * @description
 * @create 2024/4/10 10:44
 */
public class DataBaseMonitor {
    private final Logger logger = LoggerFactory.getLogger(DataBaseMonitor.class);

    private Connection conn;
    private Statement stmt;

    @Resource
    private TdengineConfig tdengineConfig;
    public DataBaseMonitor init() throws SQLException {
        if (conn == null) {
            String jdbcURL = "jdbc:TAOS-RS://192.168.130.73:6041?user=usr_app_szy&password=YXdkkxsvmv9C";
//            String jdbcURL = "jdbc:TAOS-RS://192.168.130.53:6041?user=root&password=taosdata";
            conn = DriverManager.getConnection(jdbcURL);
            stmt = conn.createStatement();
        }
        return this;
    }

    public void close() {
        try {
            stmt.close();
        } catch (SQLException e) {
            logger.error("stmt 关闭失败",e);

        }
        try {
            conn.close();
        } catch (SQLException e) {
            logger.error("conn 关闭失败",e);
        }
    }

    public void prepareDatabase() throws SQLException {
        stmt.execute("DROP DATABASE IF EXISTS test");
        stmt.execute("CREATE DATABASE test");
        stmt.execute("CREATE STABLE test.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)");
    }

    public long count() throws SQLException {
        try (ResultSet result = stmt.executeQuery("SELECT count(*) from test.meters")) {
            result.next();
            return result.getLong(1);
        }
    }

    public long getTableCount() throws SQLException {
        try (ResultSet result = stmt.executeQuery("select count(*) from information_schema.ins_tables where db_name = 'test';")) {

            return result.getLong(1);
        }
    }
}
